/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reyes.mysite.struts;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import reyes.mysite.dao.GenericDAO;
import reyes.mysite.jdo.Blog;

/**
 *
 * @author reyesyang
 */
public class QueryBlogDetailsAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        String nickTitle = request.getParameter("nickTitle");
        GenericDAO<Blog> blogDAO = new GenericDAO<Blog>();

        blogDAO.beginTransaction();
        try {
            String queryString = "select from " + Blog.class.getName() + " where nickTitle=='" + nickTitle + "'";
            List<Blog> blogs = blogDAO.query(queryString);
            if (blogs.size() == 1) {
                Blog blog = blogs.get(0);
                blog.setReadCount(blog.getReadCount() + 1);
                request.setAttribute("blog", blog);
            }
            blogDAO.commitTransaction();
        } catch (Exception e) {
            System.out.println("Can't get blog from it nickName, Details: " + e.getMessage());
        } finally {
            if (blogDAO.isActiveTransaction()) {
                blogDAO.rollbackTransaction();
            }
            blogDAO.closePM();
        }

        String destPath;
        UserService userService = UserServiceFactory.getUserService();
        if (userService.isUserLoggedIn()) {
            if (userService.isUserAdmin()) {
                destPath = "adminBlogDetails";
            } else {
                destPath = "blogDetails";
            }
        } else {
            destPath = "blogDetails";
        }

        return mapping.findForward(destPath);
    }
}
